// ManualBot.cpp : Defines the entry point for the console application.
//

#define _CRT_SECURE_NO_DEPRECATE 1
#include "stdafx.h"
#include "SittingDuckAgent.h"
#include "Visualizer.h"
#include "KalmanState.h"

#include <conio.h>   //for getch(), needed in wait_for_key()
#include <windows.h> //for Sleep()

void sleep(int i) { Sleep(i*1000); }
long GetTime();
void process_args(int argc, char* argv[]);

int _tmain(int argc, char* argv[]) {

	process_args(argc, argv);

	BZRC* remote = Remote::instance();
	World* world = World::instance();

	world->init();

	std::vector<Agent> agents;
	for(unsigned int i = 0; i < world->tanks().size(); i ++){
		agents.push_back(SittingDuckAgent(&world->tanks()[i]));
	}

	agents[0].setState(new KalmanState());

	Visualizer visualizer;
	visualizer.init(argc, argv);
	visualizer.show();

	vector<Command> commands;

	while (true) {
		commands.clear();
		long t1 = GetTime();

		// Get commands for each of the tanks
		for(unsigned int i = 0; i < agents.size(); i ++){
			commands.push_back(agents[i].GetCommand());
		}

		commands.push_back(world->update());

		remote->do_commands(commands);

		world->updateKalmanTanks();

		long t2 = GetTime();

		cout << "Loop Time: " << t2 - t1 << "ms" << endl;
	}

	cout << "Press <ENTER> to quit";
	getch();

	return 0;
}

void process_args(int argc, char* argv[]) {
	string server;
	int port;

	if(argc < 2) {
		cout << "server: ";
		cin >> server;
	}
	else {
		server = argv[1];
	}
    if(argc < 3) {
		cout << "port: ";
		cin >> port;
	}
	else {
        port = atoi(argv[2]);
    }

	cout << "Connecting...";
	Remote::init(server, port, false);

	if (!Remote::instance()->GetStatus()) {
		cout << endl << "Unable to contact server" << endl;
		exit(1);
	}
	else {
		cout << " Success!" << endl;
	}
}

long GetTime() {
	SYSTEMTIME tm;
	GetSystemTime(&tm);
	return (long)tm.wMilliseconds + 
		   (long)tm.wSecond * 1000 + 
		   (long)tm.wMinute * 60000 + 
		   (long)tm.wHour * 3600000;// + 
		   //(long)tm.wDay * 86400000;
}